<?php
declare (strict_types=1);

namespace app\backend\controller\v5;

use app\api\validate\LoginValidate;
use app\common\models\BackendMember as BackendMemerModel;
use think\exception\ValidateException;

class Teacher extends BaseController
{
    public $role_id;

    public function initialize()
    {
        $this->role_id = 3;
    }

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function read()
    {
        //搜索
        $where1 = input('username');
        $where2 = input('account');
        $this->role_id = input('role_id/d', 3);

        $model = new BackendMemerModel();
        $page = input('page/d', 1);
        $size = 10;
        $datas = $model
            ->with(['role'])
            ->where('is_del', 0)
            ->where('role_id', '=', $this->role_id)
            ->where(function ($query) use ($where1, $where2) {
                if ($where1) {
                    $query->where('username', 'like', '%' . $where1 . '%');
                }
                if ($where2) {
                    $query->where('account', 'like', '%' . $where2 . '%');
                }
            })
            ->order('id','desc')
            ->page($page, $size)
            ->select();
        foreach ($datas as $data) {
            $data['role_name'] = $data['role']['role_name'];
            unset($data['role']);
        }
        $rows = count($model->where('role_id', $this->role_id)->select());
        $maxPage = ceil($rows / $size);
        return sucessMsg(200, '获取成功！', ['data' => $datas, 'page' => $page, 'maxPage' => $maxPage, 'rows' => $rows]);
    }

    /**
     * 保存新建的资源
     *
     * @param \think\Request $request
     * @return \think\Response
     */
    public function save(\think\Request $request)
    {
        $postData = input('post.');
        $postData['role_id'] = $this->role_id;
        try {
            if (!empty($postData['id'])){
                //  验证参数
                validate(LoginValidate::class)->scene('update')->check($postData);
                $user = new \app\common\model\BackendMember();
                if (!empty($postData['password'])){
                    $postData['salt'] = getRandStr(6);
                    $postData['password_hash'] = makePassword($postData['password'], $postData['salt']);
                }
                unset($postData['password']);
                // 获取表单上传文件
                $file = request()->file('avatar');
                if (!empty($file)) {
                    // 上传
                    $savename = \think\facade\Filesystem::disk('public')->putFile('/uploads', $file);
                    $postData['avatar'] = $savename;
                }
                if ($user->update($postData)) {
                    return sucessMsg(200, '修改成功');
                }
                return errMsg(500, '修改失败');
            }else{
                //  验证参数
                validate(LoginValidate::class)->scene('save')->check($postData);
                $user = new \app\common\model\BackendMember();
                $memberInfo = $user->fetchInfoByWhere(['account' => $postData['account']], 'id,account,role_id');
                if (!empty($memberInfo)) {
                    return errMsg(422, '账号已存在！');
                }
                $postData['salt'] = getRandStr(6);
                $postData['password_hash'] = makePassword($postData['password'], $postData['salt']);
                // 获取表单上传文件
                $file = request()->file('avatar');
                if (!empty($file)) {
                    // 上传
                    $savename = \think\facade\Filesystem::disk('public')->putFile('/uploads', $file);
                    $postData['avatar'] = $savename;
                }

                if ($user->save($postData)) {
                    return sucessMsg(200, '添加成功');
                }
                return errMsg(422, '添加失败');
            }
        } catch (ValidateException $e) {
            return errMsg(400, $e->getError());
        }
    }

}